package com.sdy.mvc.filter;

import com.sdy.common.model.Response;
import com.sdy.mvc.service.FileService;
import com.sdy.mvc.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component
public class FsFilter implements Filter {
    public static final String FILE_UPLOAD_URL_GET = "/fs/upload/url";
    private static String fsUrl;
    @Autowired
    private FileService fileService;
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Response<String> respData = Response.success();
        if (fsUrl == null) {
            String fsPath = fileService.getFsUploadAddr();
            if (fsPath == null) {
                respData.setData(null);
                respData.setSuccess(false);
            } else {
                fsUrl = fsPath;
                respData.setData(fsUrl);
            }
        } else {
            respData.setData(fsUrl);
        }
        respData.setMessage(null);
        String respJson = JsonUtil.toJson(respData);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(respJson == null ? "" : respJson);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
